package com.polaris.live.ui.message.fragment.dialog

import android.app.Dialog
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import androidx.annotation.CallSuper
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import com.polaris.live.R
import com.polaris.live.interface_bag.AnimationListenerAdapter

/**
 * 可重用的DialogFragment，使用show和hide来处理，防止重复创建
 *
 * @author Created by lucas on 2023/10/28 17:36
 */
abstract class ReusableDialogFragment : DialogFragment() {

    private var mShowDialog: Boolean? = null

    @CallSuper
    override fun onStart() {
        super.onStart()

        if (isReusable) {
            val showDialog = mShowDialog
            if (showDialog != null && !showDialog) {
                dialog?.hide()
            }
        }
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return if (!isReusable) {
            super.onCreateDialog(savedInstanceState)
        } else {
            return RewriteCancelDialog(requireContext(), theme).apply {
                setOnKeyListener { _, keyCode, _ ->
                    if (keyCode == KeyEvent.KEYCODE_BACK) {
                        this@ReusableDialogFragment.hide()
                        true
                    } else {
                        false
                    }
                }
                addOnCancelListener {
                    this@ReusableDialogFragment.hide()
                    onCancel(it)
                }
            }
        }
    }

    override fun show(manager: FragmentManager, tag: String?) {
        val dialog = dialog
        if (isReusable && dialog != null) {
            mShowDialog = true

            onShow()

            view?.clearAnimation()
            view?.startAnimation(AnimationUtils.loadAnimation(context, getShowAnimation()).apply {
                setAnimationListener(object : AnimationListenerAdapter() {
                    override fun onAnimationStart(animation: Animation) {
                        view?.visibility = View.VISIBLE
                    }
                })
            })

            dialog.show()
        } else {
            if (isReusable) {
                manager.findFragmentByTag(tag)?.let {
                    manager.beginTransaction().remove(it).commit()
                }
            }

            super.show(manager, tag)
        }
    }

    override fun show(transaction: FragmentTransaction, tag: String?): Int {
        val dialog = dialog
        return if (isReusable && dialog != null) {
            mShowDialog = true

            onShow()

            dialog.show()
            -1
        } else {
            super.show(transaction, tag)
        }
    }

    override fun showNow(manager: FragmentManager, tag: String?) {
        val dialog = dialog
        if (isReusable && dialog != null) {
            mShowDialog = true

            onShow()

            dialog.show()
        } else {
            if (isReusable) {
                manager.findFragmentByTag(tag)?.let {
                    manager.beginTransaction().remove(it).commit()
                }
            }

            super.showNow(manager, tag)
        }
    }

    /**
     * 隐藏dialog
     *
     * 非可重用的情况下与[dismiss]等同
     */
    fun hide() {
        if (isReusable) {
            val showDialog = mShowDialog
            if (showDialog == null || showDialog) {
                view?.clearAnimation()
                view?.startAnimation(
                    AnimationUtils.loadAnimation(context, getHideAnimation()).apply {
                        setAnimationListener(object : AnimationListenerAdapter() {
                            override fun onAnimationEnd(animation: Animation) {
                                view?.visibility = View.INVISIBLE
                                view?.post {
                                    dialog?.hide()
                                }
                            }
                        })
                    })
            }

            mShowDialog = false
        } else {
            dismiss()
        }

    }

    open fun onShow() {
    }

    open fun getShowAnimation(): Int {
        return R.anim.slide_in_bottom
    }

    open fun getHideAnimation(): Int {
        return R.anim.slide_out_bottom
    }

    /**
     * 记住这里不要动，因为dialogfragment弹出后会有个透明的背景，这个背景会把你的点击事件栏走
     * #不要删  不要删  不要删
     */
    override fun onResume() {
        super.onResume()
        if (isReusable) {
            dialog?.window?.setBackgroundDrawableResource(android.R.color.transparent)
        }
    }

    open val isReusable = true

    fun isOnShow() = mShowDialog

}